package com.ems.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ems.entity.TMenu;
import com.ems.entity.TProduct;
import com.ems.entity.TUser;
import com.ems.entity.vo.TMenuVo;
import com.ems.mapper.TMenuMapper;
import com.ems.mapper.TProductMapper;
import com.ems.mapper.TUserMapper;
import com.ems.service.TMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZZH
 * @since 2022-06-27
 */
@Service
public class TMenuServiceImpl extends ServiceImpl<TMenuMapper, TMenu> implements TMenuService {
    @Autowired
    TMenuMapper tMenuMapper;

    //增
    @Override
    @Transactional
    public Boolean add(TMenu tMenu){
        baseMapper.add1(tMenu);
        int x = tMenu.getId();
        baseMapper.add2(x);
        return true;
    }

    //删
    @Override
    @Transactional
    public Boolean delete(Integer id){
        baseMapper.delete(id);
        baseMapper.delete2(id);
        return true;
    }

    //改
    @Override
    public Boolean update(TMenu tMenu){
        baseMapper.update(tMenu);
        return true;
    }

    //查单
    @Override
    public TMenu findOne(Integer id){
        return baseMapper.findOne(id);
    }

    //查全
    @Override
    public List<TMenu> findAll(){
        return baseMapper.findAll();
    }

    @Override
    @Transactional
    public List<TMenu> findMenuList(String userName) {
        int pid = baseMapper.findUserRole(userName);
        List<TMenu> list = baseMapper.findMenuId(pid);
        return list;
    }
    @Override
    public List<TMenuVo> treeList(String userName) {
//        List<TMenu> menuList = list();//此处默认list()查所有的，可以改成根据用户id去查菜单，或者用户role去查询菜单，mapper里面配置自己写下

        List<TMenu> menuList = findMenuList(userName);
        List<TMenuVo> result = menuList.stream()
                .filter(menu -> menu.getParentId().equals(0))
                .map(menu -> covertMenuNode(menu, menuList)).collect(Collectors.toList());
        return result;
    }
    private TMenuVo covertMenuNode(TMenu menu, List<TMenu> menuList) {
        TMenuVo node = new TMenuVo();
        BeanUtils.copyProperties(menu, node);
        List<TMenuVo> children = menuList.stream()
                .filter(subMenu -> subMenu.getParentId().equals(menu.getId()))
                .map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
        node.setChildren(children);
        System.out.println(node);
        return node;
    }
}
